<?php

namespace app\ruinuo\design;

use app\common\model\RuinuoSetting;
use app\common\model\AdminPowerTable;
use app\common\model\RuinuoApp;
use app\common\model\AdminMenu;
use app\common\model\RuinuoForm;
use app\common\model\RuinuoTable;
use app\common\model\RuinuoMode;
use app\ruinuo\design\FormLayout as CurdForm;
use app\ruinuo\design\Logic as ThatLogic;

class Curd
{

    public function SetCode($id = '')
    {
        $RuinuoSetting = new RuinuoSetting();
        $Setting = $RuinuoSetting->where("id='" . $id . "'")->findOrEmpty()->toArray();
        $app = ['name' => '配置管理', 'num' => 'setting'];
        $mode = ['name' => $Setting['num'], 'num' => $Setting['num'], 'database' => 'ruinuo_setting', 'id' => $id];
        $form = ['form_label' => $Setting['num'], 'label_width' => $Setting['label_width'], 'layout' => $Setting['layout']];
        $Config = [
            'app' => $app,
            'mode' => $mode,
            'form' => $form,
        ];
        $code = 'set_';
        $this->File($Config);//ok
        $this->ControllerPhp($Config, $code);//ok
        $this->CustomPhp($Config, $code);//ok
        $this->LogicPhp($Config, $code);//ok
        $this->FormHtml($Config);//ok
        $this->ConfigJs($Config, $code);//ok
        $this->FormJs($Config);//ok
    }


    public function FileCode($mode_id)
    {
        $RuinuoApp = new RuinuoApp();
        $RuinuoMode = new RuinuoMode();
        $RuinuoForm = new RuinuoForm();
        $RuinuoTable = new RuinuoTable();
        $mode = $RuinuoMode->where("id='" . $mode_id . "' and is_delete=0")->findOrEmpty()->toArray();
        $app = $RuinuoApp->where("id='" . $mode['app_id'] . "' and is_delete=0")->findOrEmpty()->toArray();
        $form = $RuinuoForm->where("mode_id='" . $mode_id . "' and is_delete=0")->findOrEmpty()->toArray();
        $Lists = $RuinuoTable->where("mode_id='" . $mode_id . "' and is_delete=0")->findOrEmpty()->toArray();
        $Config = [
            'app' => $app,
            'mode' => $mode,
            'form' => $form,
            'lists' => $Lists,
        ];
        if (empty($form) || empty($Lists)) {
            $this->SyncInit($Config);
            $form = $RuinuoForm->where("mode_id='" . $mode_id . "' and is_delete=0")->findOrEmpty()->toArray();
            $Lists = $RuinuoTable->where("mode_id='" . $mode_id . "' and is_delete=0")->findOrEmpty()->toArray();
            $Config = [
                'app' => $app,
                'mode' => $mode,
                'form' => $form,
                'lists' => $Lists,
            ];
        }
        $this->File($Config);//ok
        $this->ControllerPhp($Config);//ok
        $this->ModePhp($Config);//ok
        $this->CustomPhp($Config);//ok
        $this->ListsPhp($Config);//ok
        $this->LogicPhp($Config);//ok
        $this->FormHtml($Config);//ok
        $this->ListsHtml($Config);//ok
        $this->ConfigJs($Config);//ok
        $this->FormJs($Config);//ok
        $this->ListsJs($Config);//ok
    }


    /*生成控制器代码*/
    public function ControllerPhp($config, $code = '')
    {
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $mode = ucfirst(GetCamelize($config['mode']['database']));
        $path = App()->getBasePath() . "/" . $app . "/controller/" . ucfirst($controller) . ".php";
        if (!file_exists($path)) {
            $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/" . $code . "controller.tpl");
            $str = str_replace("<app>", $app, $str);
            $str = str_replace("<controller>", $controller, $str);
            $str = str_replace("<mode>", $mode, $str);
            $str = str_replace("<ID>", $config['mode']['id'], $str);
            $str = str_replace("<ccontroller>", ucfirst($controller), $str);
            getCreatetxt($path, $str);
        }

    }

    /*生成模型代码*/
    public function ModePhp($config)
    {
        $mode = ucfirst(GetCamelize($config['mode']['database']));
        $database = $config['mode']['database'];
        $path = App()->getBasePath() . "/common/model/" . $mode . ".php";
        $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/mode.tpl");
        $str = str_replace("<mode>", $mode, $str);
        $str = str_replace("<database>", $database, $str);
        getCreatetxt($path, $str);
    }


    /*生成列表代码*/
    public function ListsPhp($config)
    {
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $database = $config['mode']['database'];
        $mode = ucfirst(GetCamelize($database));
        $ListModel = "\$DB=\$Model->alias('a')";
        $sub_database = !empty($config['mode']['sub_database']) ? json_decode($config['mode']['sub_database'], true) : [];
        foreach ($sub_database as $k => $v) {
            if ($v['type'] == 1) {
                if ($v['database'] == 'ruinuo_flow_status') {
                    $ListModel .= PHP_EOL . "            ->leftJoin('" . $v['database'] . " " . $v['alias'] . "', 'a." . $v['key_field'] . "= " . $v['alias'] . "." . $v['sub_field'] . " and " . $v['alias'] . ".mode_id=" . $config['mode']['id'] . "')";
                } else {
                    $ListModel .= PHP_EOL . "            ->leftJoin('" . $v['database'] . " " . $v['alias'] . "', 'a." . $v['key_field'] . "= " . $v['alias'] . "." . $v['sub_field'] . "')";
                }

            } else {
                $ListModel .= PHP_EOL . "            ->Join('" . $v['database'] . " " . $v['alias'] . "', 'a." . $v['sub_field'] . "= " . $v['alias'] . "." . $v['key_field'] . "')";
            }
        }
        $ListModel .= ";";
        $table = !empty($config['lists']) ? $config['lists'] : [];
        $cols = !empty($table['table_cols']) ? json_decode($table['table_cols'], true) : [];
        $info = $this->QueryData($cols);
        $tab = !empty($table['table_tab']) ? json_decode($table['table_tab'], true) : [];
        $table_tab = [];
        foreach ($tab as $k => $v) {
            $current = $k + 1;
            $table_tab[] = ['name' => $v['name'], 'current' => $current, 'rule' => $v['rule']];
        }


        $QueryWhere = '$where=[];' . PHP_EOL;
        if (!empty($info['like'])) {
            $QueryWhere .= "        if (!empty(\$params['keyword'])) {" . PHP_EOL;
            $QueryWhere .= "            \$where[] = ['" . $info['like'] . "', 'like', '%' . \$params['keyword'] . '%'];" . PHP_EOL;
            $QueryWhere .= '        }' . PHP_EOL;
        }
        if (!empty($info['equal'])) {
            $equal = explode('|', $info['equal']);
            foreach ($equal as $k => $v) {
                if ($v) {
                    $t = explode('.', $v);
                    $QueryWhere .= "        if (!empty(\$params['" . $t[1] . "'])) {" . PHP_EOL;
                    $QueryWhere .= "            \$where[] = ['" . $v . "', '=', \$params['" . $t[1] . "']];" . PHP_EOL;
                    $QueryWhere .= "        }" . PHP_EOL;
                }
            }
        }
        if (!empty($info['datetime'])) {
            $datetime = explode('|', $info['datetime']);
            foreach ($datetime as $k => $v) {
                if ($v) {
                    $t = explode('.', $v);
                    $QueryWhere .= "        \$datetime=!empty(\$params['" . $t[1] . "']) ? json_decode(\$params['" . $t[1] . "'],true) : [];" . PHP_EOL;
                    $QueryWhere .= "        if (!empty(\$datetime['start_time'])){" . PHP_EOL;
                    $QueryWhere .= "            \$where[] = ['" . $v . "', '>=', \$datetime['start_time']];" . PHP_EOL;
                    $QueryWhere .= "        }" . PHP_EOL;
                    $QueryWhere .= "        if (!empty(\$datetime['end_time'])){" . PHP_EOL;
                    $QueryWhere .= "            \$where[] = ['" . $v . "', '<=', \$datetime['end_time']];" . PHP_EOL;
                    $QueryWhere .= "        }" . PHP_EOL;
                }
            }
        }

        $QueryWhere .= "        if (!empty(\$params['choose_ids'])){" . PHP_EOL;
        $QueryWhere .= "            \$where[] = ['a.id', 'in', \$params['choose_ids']];" . PHP_EOL;
        $QueryWhere .= "        }" . PHP_EOL;


        $path = App()->getBasePath() . "/" . $app . "/service/" . $controller . "/Lists.php";
        $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/lists.tpl");
        $str = str_replace("<app>", $app, $str);
        $str = str_replace("<controller>", $controller, $str);
        $str = str_replace("<mode>", $mode, $str);
        $str = str_replace("<mode_name>", $config['mode']['name'], $str);
        $str = str_replace("<ListModel>", $ListModel, $str);
        $str = str_replace("<QueryWhere>", $QueryWhere, $str);
        $str = str_replace("<ListFleid>", $info['fields'], $str);
        $AscDesc = !empty($table['asc_desc']) ? $table['asc_desc'] : 'a.create_time desc';
        if ($AscDesc == 'id desc') {
            $AscDesc = 'a.create_time desc';
        }
        $str = str_replace("<AscDesc>", $AscDesc, $str);
        $SumCount = '';
        foreach ($info['count'] as $k => $v) {
            $SumCount .= "            ['name'=>'" . $v['name'] . "','field'=>'" . $v['show_field'] . "','num'=>\$this->GetSum(\$params,'" . $v['field'] . "')]," . PHP_EOL;
        }
        if ($SumCount) {
            $SumCount = '$data=[' . PHP_EOL . '' . $SumCount . '        ];';
        } else {
            $SumCount = '$data=[];';
        }
        $str = str_replace("<SumCount>", $SumCount, $str);
        $TabCount = '';
        $SetWhere = !empty($table['set_where']) ? $table['set_where'] . ' and a.is_delete=0' : 'a.is_delete=0';
        $TabWhere = "\$where='" . $SetWhere . "';" . PHP_EOL;
        foreach ($table_tab as $k => $v) {
            $TabWhere .= '        if ($current==' . $v['current'] . '){' . PHP_EOL;
            $TabWhere .= '            $where.=" and ' . $v['rule'] . '";' . PHP_EOL;
            $TabWhere .= '        }' . PHP_EOL;
            $TabCount .= "            ['name'=>'" . $v['name'] . "','current'=>'" . $v['current'] . "','num'=>\$this->GetTab(\$params," . $v['current'] . ")]," . PHP_EOL;
        }
        if ($TabCount) {
            $TabCount = '$data=[' . PHP_EOL . '' . $TabCount . '        ];';
        } else {
            $TabCount = '$data=[];';
        }
        $str = str_replace("<TabCount>", $TabCount, $str);
        $str = str_replace("<TabWhere>", $TabWhere, $str);
        $ExcelField = '';
        $layout = !empty($config['form']['layout']) ? json_decode($config['form']['layout'], true) : [];
        $CurdForm = new CurdForm();
        $Form = $CurdForm->GetFormField($layout);
        foreach ($Form as $k => $v) {
            $required = !empty($v['required']) ? $v['required'] : 2;
            $start = '';
            if ($required == 1) {
                $start = '(必填)';
            }
            if ($v['tag'] != 'ordernum') {
                $ExcelField .= "            ['field'=>'" . $v['field'] . "','title'=>'" . $v['title'] . $start . "']," . PHP_EOL;
            }
        }
        if ($ExcelField) {
            $ExcelField = '$field=[' . PHP_EOL . '' . $ExcelField . '        ];';
        } else {
            $ExcelField = '$field=[];';
        }
        $str = str_replace("<ExcelField>", $ExcelField, $str);
        $OutExcel = '';
        foreach ($cols as $k => $v) {
            $OutExcel .= "            ['field'=>'" . $v['field'] . "','title'=>'" . $v['title'] . "']," . PHP_EOL;
        }
        if ($OutExcel) {
            $OutExcel = '$excel_field=[' . PHP_EOL . '' . $OutExcel . '        ];';
        } else {
            $OutExcel = '$excel_field=[];';
        }
        $str = str_replace("<OutExcel>", $OutExcel, $str);

        getCreatetxt($path, $str);
    }

    public function QueryData($cols = [])
    {

        $search = [
            'like' => '',
            'datetime' => '',
            'equal' => '',
            'fields' => '',
        ];
        $countArr = [];
        foreach ($cols as $k => $v) {
            $se = !empty($v['search']) ? $v['search'] : '';
            $show_field = $v['field'];
            $fields = explode('__', $v['field']);
            if (count($fields) == 1) {
                $v['field'] = 'a.' . $v['field'];
                $search['fields'] .= $v['field'] . ',';
            } else {
                $search['fields'] .= $fields[0] . '.' . $fields[1] . ' as ' . $v['field'] . ',';
                $v['field'] = $fields[0] . '.' . $fields[1];
            }

            $count = !empty($v['count']) ? $v['count'] : 2;
            if ($count == 1) {
                $countArr[] = [
                    'name' => $v['title'],
                    'field' => $v['field'],
                    'show_field' => $show_field,
                ];
            }


            switch ($se) {
                case "like":
                    $search['like'] .= $v['field'] . '|';
                    break;
                case "datetime":
                    $search['datetime'] .= $v['field'] . '|';
                    break;
                case "select":
                case "url":
                    $search['equal'] .= $v['field'] . '|';
                    break;
            }
        }
        if (count(explode('a.id,', $search['fields'])) == 1) {
            $search['fields'] = 'a.id,' . $search['fields'];
        }
        $search = [
            'like' => rtrim($search['like'], "|"),
            'datetime' => rtrim($search['datetime'], "|"),
            'equal' => rtrim($search['equal'], "|"),
            'fields' => rtrim($search['fields'], ","),
            'count' => $countArr,
        ];
        return $search;
    }

    public function CustomPhp($config, $code = '')
    {
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $database = $config['mode']['database'];
        $mode = ucfirst(GetCamelize($database));
        $path = App()->getBasePath() . "/" . $app . "/service/" . $controller . "/Custom.php";
        $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/" . $code . "custom.tpl");
        $str = str_replace("<app>", $app, $str);
        $str = str_replace("<controller>", $controller, $str);
        $str = str_replace("<mode>", $mode, $str);
        if (!file_exists($path)) {
            getCreatetxt($path, $str);
        }
    }

    /*生成增删改查代码*/
    public function LogicPhp($config, $code = '')
    {

        $CurdForm = new CurdForm();
        $ThatLogic = new ThatLogic();
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $mode = ucfirst(GetCamelize($config['mode']['database']));
        $sub_database = !empty($config['mode']['sub_database']) ? json_decode($config['mode']['sub_database'], true) : [];
        $layout = !empty($config['form']['layout']) ? json_decode($config['form']['layout'], true) : [];
        $Form = $CurdForm->GetFormField($layout);
        $NewForm = [];
        $subTable = [];
        foreach ($Form as $k => $v) {
            $item = [
                'field' => !empty($v['field']) ? $v['field'] : '',
                'title' => !empty($v['title']) ? $v['title'] : '',
                'value' => isset($v['value']) ? $v['value'] : '',
                'tag' => !empty($v['tag']) ? $v['tag'] : '',
                'only' => !empty($v['only']) ? $v['only'] : 2,
                'required' => !empty($v['required']) ? $v['required'] : 2,
                'verify' => !empty($v['verify']) ? $v['verify'] : '',
            ];
            if (!empty($v['range_field'])) {
                $item['range_field'] = $v['range_field'];
            }
            if (!empty($v['options_num'])) {
                $item['options_num'] = $v['options_num'];
            }
            if (!empty($v['cols'])) {
                $item['cols'] = $v['cols'];
            }

            if (!empty($v['database'])) {
                $item['database'] = $v['database'];
            }
            if (!empty($v['database_field'])) {
                $item['database_field'] = $v['database_field'];
            }

            if (!empty($v['num_rule'])) {
                $item['num_rule'] = $v['num_rule'];
            }
            if (!empty($v['event_val'])) {
                $item['event_val'] = $v['event_val'];
            }
            $str_field = '';
            $cols = !empty($item['cols']) ? $item['cols'] : [];
            foreach ($cols as $k3 => $v3) {
                $str_field .= $v3['field'] . ',';
            }
            if ($v['tag'] == 'subtable') {
                $Modes = new RuinuoMode();
                $mode_id = !empty($v['mode_id']) ? $v['mode_id'] : 0;
                $mode_sub_id = !empty($v['mode_sub_id']) ? $v['mode_sub_id'] : 0;
                $base = $Modes->where("id='" . $mode_id . "'")->field("database")->find();
                $database = !empty($base['database']) ? $base['database'] : '';
                $subTable[] = [
                    'database' => $database,
                    'tag' => $v['tag'],
                    'sub_id' => $mode_sub_id,
                    'field' => $item['field'],
                    'str_field' => rtrim($str_field, ','),
                ];
            }
            if ($v['tag'] == 'designtable') {
                $subTable[] = [
                    'database' => $v['database'],
                    'tag' => $v['tag'],
                    'sub_id' => $v['database_field'],
                    'field' => $item['field'],
                    'str_field' => rtrim($str_field, ','),
                ];
            }
            $NewForm[] = $item;
        }


        $path = App()->getBasePath() . "/" . $app . "/service/" . $controller . "/Logic.php";
        $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/" . $code . "logic.tpl");
        $options_num = $ThatLogic->OptionsNum($NewForm);
        $verify = $ThatLogic->GetVerify($NewForm, $config['mode']);
        $DetailField = $ThatLogic->DetailField($NewForm);
        $DesignTable = $ThatLogic->DesignTable($NewForm);
        $DetailModel = $ThatLogic->DetailModel($config['mode']);
        $FormData = $ThatLogic->FormData($NewForm, $config['mode']);
        $DataBase = $ThatLogic->DataBase($subTable, $sub_database);
        $str = str_replace("<app>", $app, $str);
        $str = str_replace("<controller>", $controller, $str);
        $str = str_replace("<mode>", $mode, $str);
        $str = str_replace("<DetailModel>", $DetailModel, $str);
        $str = str_replace("<DetailField>", $DetailField, $str);
        $str = str_replace("<key_database>", $config['mode']['database'], $str);
        $str = str_replace("<options_num>", $options_num, $str);
        $str = str_replace("<FormData>", $FormData, $str);
        $str = str_replace("<verify>", $verify, $str);
        $str = str_replace("<DesignTable>", $DesignTable, $str);
        $str = str_replace("<DataBase>", $DataBase, $str);
        return getCreatetxt($path, $str);
    }


    /*生成表单HTML代码*/
    public function FormHtml($config)
    {
        $CurdForm = new CurdForm();
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $title = $config['mode']['name'];
        $layout = !empty($config['form']['layout']) ? json_decode($config['form']['layout'], true) : [];
        $html = $CurdForm->GetForm($layout);
        $bind = $CurdForm->GetJs($layout);
        $path = App()->getBasePath() . "/common/template/" . $app . "/" . $controller . "/form.html";
        $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/form.html");
        $str = str_replace("<app>", $app, $str);
        $str = str_replace("<controller>", $controller, $str);
        $str = str_replace("<-title>", $title, $str);
        $str = str_replace("<html>", $html, $str);
        $str = str_replace("let bind='';", $bind, $str);
        getCreatetxt($path, $str);
    }

    /*生成列表HTML代码*/
    public function ListsHtml($config)
    {
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $title = $config['mode']['name'];
        $table = !empty($config['lists']) ? $config['lists'] : [];
        $style = !empty($table['style']) ? $table['style'] : 1;

        $path = App()->getBasePath() . "/common/template/" . $app . "/" . $controller . "/lists.html";
        $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/lists.html");
        $str = str_replace("<app>", $app, $str);
        $str = str_replace("<controller>", $controller, $str);
        $str = str_replace("<-title>", $title, $str);
        $table_tpl = '';
        $style_tpl = '';
        if ($style >= 4) {
            $style_tpl .= '<script type="text/html" id="datatable_tpl">' . PHP_EOL;
            $style_tpl .= '{{# layui.each(d, function(kk, group){ }}' . PHP_EOL;
            $style_tpl .= "<div class='layui-row layui-col-space15 row-hight'>" . PHP_EOL;
            $style_tpl .= '{{# layui.each(group, function(index, item){ }}' . PHP_EOL;
            $style_tpl .= '<div class="layui-col-md3 card_data_table" data-id="{{item.id}}"  data-index="{{index}}">' . PHP_EOL;
            $style_tpl .= $table['style_tpl'] . PHP_EOL;
            $style_tpl .= '</div>' . PHP_EOL;
            $style_tpl .= '{{# }); }}' . PHP_EOL;
            $style_tpl .= "</div>" . PHP_EOL;
            $style_tpl .= '{{# }); }}' . PHP_EOL;
            $style_tpl .= '{{# if(d.length == 0){ }}' . PHP_EOL;
            $style_tpl .= '<div class="nodata_con"><div class="ruinuo-icon icon-meiyoushuju"></div><div class="desc">暂无数据</div></div>' . PHP_EOL;
            $style_tpl .= '{{# } }}' . PHP_EOL;
            $style_tpl .= '</script>' . PHP_EOL;
        }


        $Lists = !empty($config['lists']) ? $config['lists'] : [];

        $cols = !empty($Lists['table_cols']) ? json_decode($Lists['table_cols'], true) : [];

        foreach ($cols as $kk => $vv) {
            if (!empty($vv['tpl'])) {
                $table_tpl .= '<script type="text/html" id="tpl_' . $vv['id'] . '">' . PHP_EOL;
                $table_tpl .= $vv['tpl'] . PHP_EOL;
                $table_tpl .= '</script>' . PHP_EOL;
            }
        }


        $str = str_replace("<style_tpl>", $style_tpl, $str);
        $str = str_replace("<table_tpl>", $table_tpl, $str);
        getCreatetxt($path, $str);
    }

    /*生成配置JS代码*/
    public function ConfigJs($config, $code = '')
    {
        $AdminMenu = new AdminMenu();
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $label_width = !empty($config['form']['label_width']) ? $config['form']['label_width'] : '';
        $form_label = !empty($config['form']['form_label']) ? $config['form']['form_label'] : 'form_right';
        $tableConfig = [];
        if ($code == '') {

            $table = !empty($config['lists']) ? $config['lists'] : [];
            $cols = !empty($table['table_cols']) ? json_decode($table['table_cols'], true) : [];
            $tab = !empty($table['table_tab']) ? json_decode($table['table_tab'], true) : [];
            $table_tab = [];
            $node = "" . $app . ":" . $controller . ":index";
            $menu = $AdminMenu->where("power_node='" . $node . "' and type=2 and is_delete=0")->field("id")->findOrEmpty()->toArray();
            if ($menu) {
                $field = 'title,icon,btn_class,is_drop,open_type as type,href as url,where,width,height,power_node as node';
                $button_head = $AdminMenu->where("parent_id='" . $menu['id'] . "' and status=1 and type=3 and position=1 and is_delete=0")->field($field)->order('sort asc,id desc')->select()->toArray();
                $button_table = $AdminMenu->where("parent_id='" . $menu['id'] . "' and status=1 and type=3 and position=2 and is_delete=0")->field($field)->order('sort asc,id desc')->select()->toArray();
            }
            foreach ($tab as $k => $v) {
                $current = $k + 1;
                $table_tab[] = ['name' => $v['name'], 'current' => $current];
            }
            $source = '';
            $sum = [];
            $datetime = [];
            $like = '';

            foreach ($cols as $kk => $vv) {
                if (!empty($vv['hide'])) {
                    if ($vv['hide'] != 1) {
                        unset($cols[$kk]['hide']);
                    }
                }
                $search = !empty($vv['search']) ? $vv['search'] : '';
                switch ($search) {
                    case "datetime":
                        $datetime[] = ['value' => $vv['field'], 'label' => $vv['title']];
                        break;
                    case "like":
                        $like .= $vv['title'] . '|';
                        break;
                }


                $field = !empty($vv['field']) ? $vv['field'] : '';
                if ($field == 'id' && empty($vv['width'])) {
                    $vv['width'] = 70;
                }
                if ($field == 'create_time' && empty($vv['width'])) {
                    $vv['width'] = 160;
                }
                if ($field == 'update_time' && empty($vv['width'])) {
                    $vv['width'] = 160;
                }
                if (!empty($vv['width'])) {
                    $cols[$kk]['width'] = $vv['width'];
                    $cols[$kk]['minWidth'] = $vv['width'];
                } else {
                    unset($cols[$kk]['width']);
                }
                if (!empty($vv['tpl'])) {
                    $cols[$kk]['tpl'] = "#tpl_" . $vv['id'];
                }

                if (!empty($vv['search'])) {
                    if ($vv['search'] != 'select') {
                        unset($cols[$kk]['search']);
                    }
                }
                $show_rule = !empty($vv['show_rule']) ? json_decode($vv['show_rule'], true) : [];
                $cols[$kk]['show_rule'] = $show_rule;
                if (empty($show_rule)) {
                    unset($cols[$kk]['show_rule']);
                }

                if (!empty($vv['options'])) {
                    $source .= $vv['options'] . ',';
                }
                $count = !empty($vv['count']) ? $vv['count'] : 2;
                if ($count == 1) {
                    $sum[] = [
                        'name' => $vv['title'],
                        'field' => $field,
                    ];
                }
            }
            $page = true;
            if ($table['page_num'] == 999 || $table['style'] == 3) {
                $page = false;
            }
            $urls = [
                'title' => '',
                'list' => '/common/options/leftlists/?num=' . $table['left_options'],
                'add' => '',
                'edit' => '',
                'delete' => '',
                'width' => '',
                'height' => '',
            ];
            if ($table['left_type'] == 2 && $table['is_left'] == 1) {
                $RuinuoMode = new RuinuoMode();
                $RuinuoApp = new RuinuoApp();
                $findMode = $RuinuoMode->where("id='" . $table['left_mode'] . "'")->field('num,app_id')->findOrEmpty()->toArray();
                $findApp = $RuinuoApp->where("id='" . $findMode['app_id'] . "'")->field('num')->findOrEmpty()->toArray();
                $url = "/" . $findApp['num'] . "/" . $findMode['num'];
                $urls = [
                    'list' => $url . "/index/",
                    'add' => $url . "/add/",
                    'edit' => $url . "/edit/",
                    'delete' => $url . "/delete/",
                ];
            }
            $tab_sum = '';
            $height = 'full-85';
            if (!empty($tab) || !empty($sum)) {
                $tab_sum = '/' . $app . '/' . $controller . '/tabsum/';
                $height = 'full-130';
            }


            $tableConfig = [
                'header' => [
                    'button' => !empty($button_head) ? $button_head : [],
                    'tab' => $table_tab,
                    'search' => [
                        'datetime' => $datetime,
                        'like' => rtrim($like, '|')
                    ],
                    'sum' => $sum,
                ],
                'left' => [
                    'status' => !empty($table['is_left']) ? $table['is_left'] : 2,
                    'title' => $table['left_title'],
                    'options_id' => $table['left_options'],
                    'key_field' => $table['left_key_field'],
                    'show_field' => $table['left_show_field'],
                    'field' => $table['left_field'],
                    'type' => $table['left_type'],
                    'url' => $urls
                ],
                'source' => rtrim($source, ","),
                'table' => [
                    'button' => !empty($button_table) ? $button_table : [],
                    'style' => $table['style'],
                    'parent_id' => $table['tree_field'] ?: 'parent_id',
                    'parent_name' => $table['tree_name'] ?: 'title',
                    'limit' => !empty($page) ? $table['page_num'] : 0,
                    'tab_sum' => $tab_sum,
                    'page' => $page,
                    'elem' => 'datatable',
                    'height' => $height,
                    'update' => '/' . $app . '/' . $controller . '/update_field/',
                    'url' => '/' . $app . '/' . $controller . '/index/',
                    'cols' => $cols,
                ],
            ];
        }
        $table_config = json_encode($tableConfig, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        $table_config = str_replace('\\', '', $table_config);
        $path = 'static/js/' . $app . '/' . $controller . '/config.js';
        $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/config.js");
        $str = str_replace("<app>", $app, $str);
        $str = str_replace("<controller>", $controller, $str);
        $str = str_replace("<label_width>", $label_width, $str);
        $str = str_replace("<form_label>", $form_label, $str);
        $str = str_replace("'<table_config>'", $table_config, $str);
        $CurdForm = new CurdForm();
        $layout = !empty($config['form']['layout']) ? json_decode($config['form']['layout'], true) : [];
        $fields = $CurdForm->GetFormField($layout);
        $onclick = [];
        $formdata = [];
        foreach ($fields as $k => $v) {
            if (!empty($v['field'])) {
                $formdata[$v['field']] = isset($v['value']) ? $v['value'] : '';
            }
            $event_val = !empty($v['event_val']) ? $v['event_val'] : [];
            $gongshi_txt = !empty($v['gongshi_txt']) ? $v['gongshi_txt'] : '';
            foreach ($event_val as $k2 => $v2) {
                $v2['field'] = $v['field'];
                $v2['tag'] = $v['tag'];
                $onclick[] = $v2;
            }
            if ($gongshi_txt) {
                $onclick[] = [
                    'field' => $v['field'],
                    'tag' => $v['tag'],
                    'gongshi_txt' => $gongshi_txt,
                ];
            }
        }
        $formdata = json_encode($formdata, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        $onclick = json_encode($onclick, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        $str = str_replace("'<onclick>'", $onclick, $str);
        $str = str_replace("'<data>'", $formdata, $str);
        getCreatetxt($path, $str);
    }

    /*生成表单JS代码*/
    public function FormJs($config)
    {
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $path = 'static/js/' . $app . '/' . $controller . '/form.js';
        if (!file_exists($path)) {
            $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/form.js");
            getCreatetxt($path, $str);
        }
    }

    /*生成列表JS代码*/
    public function ListsJs($config)
    {
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $path = 'static/js/' . $app . '/' . $controller . '/lists.js';
        if (!file_exists($path)) {
            $str = file_get_contents(App()->getBasePath() . "/ruinuo/codetpl/lists.js");
            getCreatetxt($path, $str);
        }
    }

    public function File($config)
    {
        $app = $config['app']['num'];
        $controller = $config['mode']['num'];
        $file = [
            App()->getBasePath() . $app . '/',
            App()->getBasePath() . $app . '/controller/',
            App()->getBasePath() . $app . '/service/',
            App()->getBasePath() . $app . '/service/' . $controller . '/',
            App()->getBasePath() . 'common/template/' . $app . '/' . $controller . '/',
            'static/js/' . $app . '/',
            'static/js/' . $app . '/' . $controller . '/',
        ];
        foreach ($file as $k => $v) {
            if (!file_exists($v)) {
                mkdir($v, 0777, true);
            }
        }
    }

    public function SyncInit($config)
    {
        $RuinuoTable = new RuinuoTable();
        $RuinuoForm = new RuinuoForm();
        if (empty($config['form'])) {
            $upData = [
                'mode_id' => $config['mode']['id'],
                'id' => GetSnowID()
            ];
            $RuinuoForm->save($upData);
        }
        $Lists = $config['lists'];
        if (empty($Lists)) {
            $cols = [
                ['field' => 'create_id', 'title' => '新增人', 'width' => 120, 'id' => 'm_2' . time()],
                ['field' => 'create_time', 'title' => '新增时间', 'width' => 160, 'id' => 'm_1' . time()],
            ];
            $upData = [
                'id' => GetSnowID(),
                'mode_id' => $config['mode']['id'],
                'name' => $config['mode']['name'],
                'asc_desc' => 'id desc',
                'style' => 1,
                'page_num' => 30,
                'is_left' => 2,
                'table_cols' => json_encode($cols, JSON_UNESCAPED_UNICODE)
            ];
            $RuinuoTable->save($upData);
        }
    }

}